package net.mingsoft.basic.util;

import com.google.common.io.Files;
import net.mingsoft.document.dao.FileDao;
import net.mingsoft.document.entity.FileEntity;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import java.io.*;
import java.lang.reflect.Field;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author gengfa
 * @date 22/01/25
 */
@Component
public class ZipUtil {

    @Resource
    private FileDao fileDao;

    private static FileDao fileStaticDao;

    private static Field FIELD;

    @PostConstruct
    public void init() {
        fileStaticDao = fileDao;
    }

    static {
        try {
            FIELD = ZipEntry.class.getDeclaredField("name");
            FIELD.setAccessible(true);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    private ZipUtil() {}

    public static void compressZipFile(String sourceDir, ServletOutputStream outputStream) throws IOException, FileNotFoundException {
        ZipOutputStream zipFile = new ZipOutputStream(outputStream);
        Path srcPath = Paths.get(sourceDir);
        compressDirectoryToZipFile(srcPath.getParent().toString(), srcPath.getFileName().toString(), zipFile);
        IOUtils.closeQuietly(zipFile);
    }

    private static void compressDirectoryToZipFile(String rootDir, String sourceDir, ZipOutputStream out) throws IOException, FileNotFoundException {
        String dir = Paths.get(rootDir, sourceDir).toString();
        for (File file : Objects.requireNonNull(new File(dir).listFiles())) {
            if (file.isDirectory()) {
                compressDirectoryToZipFile(rootDir, Paths.get(sourceDir,file.getName()).toString(), out);
            } else {
                ZipEntry entry = new ZipEntry(Paths.get(sourceDir,file.getName()).toString());
                out.putNextEntry(rename(entry));

                FileInputStream in = new FileInputStream(Paths.get(rootDir, sourceDir, file.getName()).toString());
                IOUtils.copy(in, out);
                IOUtils.closeQuietly(in);
            }
        }
    }

    private static ZipEntry rename(ZipEntry nextEntry) {
        try {
            @SuppressWarnings("all")
            String fileId = Files.getNameWithoutExtension(nextEntry.getName());
            FileEntity entity = fileStaticDao.selectOne(fileId, null);
            String parentPath = Paths.get(entity.getFilePath()).getParent().toString();
            FIELD.set(nextEntry, parentPath + File.separator + entity.getFileCode() + "_" + entity.getFileOriginName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nextEntry;
    }

}
